import json
import os
import threading
from datetime import datetime
from tkinter import Label, Button, Entry, filedialog, ttk
from tkinter.ttk import Combobox

import regex as re
import tkinter as tk

from util.comm.AsyncTask import AsyncTask
from util.comm.cmd_util import wrap_with_try_except
from util.comm.constants import LIST_A_Z
from util.comm.msg_util import msg
from util.comm.notepad import watch_html_temp
from util.comm.path import getConfigPath, getPath
from util.database.comm_data import query_1p, list_to_str
from util.window.config_window.config_button import create_config_button


class SqlInit():
    def __init__(self):
        super().__init__()

    def frame(self, tab):
        self.tab = tab

        self.elements = []

        self.config_path = getConfigPath()
        self.button = create_config_button(self, True)

        self.menu = ttk.Frame(tab)
        self.menu.pack()
        self.elements.append(self.menu)

        self.label = Label(self.menu, text="类文件", width=7)
        self.label.grid(row=0, column=1, padx=0, pady=10)

        self.entry = Entry(self.menu, width=44)
        self.entry.grid(row=0, column=2, padx=2, pady=10)

        self.open_button = Button(self.menu, text="选择文件", command=self.open_file)
        self.open_button.grid(row=0, column=3, padx=2, pady=10)

        self.database_label = Label(self.menu, text="数据库", width=7)
        self.database_label.grid(row=1, column=1, padx=0, pady=10)

        self.dropdown = Combobox(self.menu, width=42)

        # 打开文件并读取JSON数据
        with open(self.config_path, 'r', encoding="utf-8") as file:
            data = json.load(file)
        self.drop_list = []
        self.drop_config_list = []
        if isinstance(data, list):
            for index, c in enumerate(data):
                self.drop_list.append(c['name'])
                self.drop_config_list.append(c)
        else:
            print(data)
        self.dropdown['values'] = self.drop_list
        self.dropdown.current(0)
        self.config = self.drop_config_list[0]
        self.dropdown.grid(row=1, column=2, padx=2, pady=10)
        self.dropdown.bind("<<ComboboxSelected>>", self.select_item)

        self.tables_label = Label(self.menu, text="表名", width=7)
        self.tables_label.grid(row=2, column=1, padx=0, pady=10)

        self.tables_entry = Entry(self.menu, width=44)
        self.tables_entry.grid(row=2, column=2, padx=2, pady=10)

        self.button = Button(self.menu, text="查询字段", command=self.print_entry_sync)
        self.button.grid(row=3, column=2, padx=5, pady=10)

    def open_file(self):
        file_path = filedialog.askopenfilename()
        if file_path:
            file_name = os.path.basename(file_path)
            if file_name.endswith('.java'):
                self.entry.delete(0, tk.END)
                print(f"Selected file: {file_path}")
                self.entry.insert(0, f"{file_name}")
                self.java_path = file_path
                self.class_name = file_name.replace(".java", "")
            else:
                msg("请选择.java文件")

    def select_item(self, event):
        index = self.dropdown.current()
        print('select_item----%s' % index)
        self.config = self.drop_config_list[index]

    def print_entry_sync(self):
        if hasattr(self, 'sync_flag') and self.sync_flag == '1':
            msg('正在处理,请勿重复操作')
            return
        self.sync_flag = '1'
        wrap_print_entry = wrap_with_try_except(self.print_entry)
        AsyncTask(threading.Thread(target=wrap_print_entry, args=()), lambda: self.reset_sync()).execute_async()

    def reset_sync(self):
        self.sync_flag = '0'

    def print_entry(self, clipboard=None):
        if hasattr(self, 'label_out'):
            self.label_out.destroy()

        # 当前时间戳
        s = datetime.now()

        if self.java_path:
            with open(self.java_path, 'r', encoding='utf-8') as f:
                text = f.read()

        pattern = r'(?<=private\s+[A-z]+\s+)\w+\s?;'
        matches = re.findall(pattern, text)

        sql_text = f'-- {self.class_name}<br/><br/>'
        sql_text += 'select<br/>'

        table_map = {}
        sql = self.config['sql']
        if self.tables_entry.get():
            tables = self.tables_entry.get()
            if tables.find(",") > -1:
                tables = tables.replace(",", "','")
            elif tables.find("，") > -1 :
                tables = tables.replace("，", "','")
            elif tables.find(" ") > -1:
                tables = tables.replace(" ", "','")

            tables = f"'{tables}'"
            sql = sql.replace('@table_range@', f'tc.table_name in ({tables})')

            tables_str = tables.replace("'", "")
            tables_list = tables_str.split(",")
            for index, table in enumerate(tables_list):
                table = table.lower()
                table_map[table] = LIST_A_Z[index]

        else:
            table_map.put('temp', '?')
            sql = sql.replace('@table_range@', '1=1')

        markdown_text = "|字段|字段名|库名|表名|备注|类型|\\n"
        markdown_text += "|---|---|---|---|---|---|\\n"

        if matches:
            for match in matches:
                field_name = match.replace(";", "")

                filed_str, string_str = list_to_str(query_1p(sql, field_name, self.config), field_name)
                try:
                    if filed_str.index('?') == -1:
                        pass
                except ValueError:
                    for k, v in table_map.items():
                        filed_str = filed_str.replace(k+'.', v+'.')
                sql_text += f'&nbsp;&nbsp;&nbsp;&nbsp;{filed_str}'
                markdown_text += string_str
        # 去掉最后一个,<br/>
        if sql_text.endswith(',<br/>'):
            sql_text = sql_text[:-6] + "<br/>"
        sql_text += 'from<br/>'
        for k,v in table_map.items():
            sql_text += f'&nbsp;&nbsp;&nbsp;&nbsp;{k} {v},<br/>'
        # 去掉最后一个逗号
        if sql_text.endswith(',<br/>'):
            sql_text = sql_text[:-6] + "<br/>"

        # 当前时间戳
        e = datetime.now()

        project_path = getPath()
        modal_path = os.path.join(project_path, 'modal_sql.html')
        with open(modal_path, 'r', encoding='utf-8') as f:
            html_text = f.read()
        html_text = html_text.replace('@sql_text@', sql_text)
        html_text = html_text.replace('@markdown_text@', markdown_text)

        watch_html_temp(html_text)

        self.label_out = Label(self.tab, text="结果：已输出【%s】耗时【%s】" % (datetime.now(), e-s))
        self.label_out.pack()



